<template>
<highlightjs language="JavaScript" highlightAuto top :code="code" />
</template>
<script>
export default {
  setup () {
    const code = `
    const state = reactive({
      map: ref(null),
      mapBox: ref(null)
    })

    const init = () => {
      const count = 2000 // 点的数量
      const features = [] // 存放点要素的数组

      // 初始化每个点的坐标位置
      const e = 4500000
      for (let i = 0; i < count; ++i) {
        const coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e]
        // 根据坐标生成点状几何
        features[i] = new Feature(new Point(coordinates))
      }

      // 创建矢量容器，将图标特性添加进容器中
      const vectorSource = new VectorSource({
        features: features
      })

      const clusterSource = new Cluster({
        // 通过 distance 来控制两个点聚合的间距，如果2个点的间距小于 distance 所设置的数时，就会以聚合的方式显示
        distance: parseInt(40, 10),
        source: vectorSource // 就是前面用到的矢量数据源
      })

      // 点的样式
      const styleCache = {}
      const clusters = new VectorLayer({
        source: clusterSource, // 源，指向上面的聚合数据源
        style: feature => { // feature 是聚合后的数据，每一个 feature 代表距离小于上面设置的点状要素
          const size = feature.get('features').length // features 是点状要素
          let style = styleCache[size]

          if (!style) {
            style = new Style({
              image: new Circle({
                radius: 10,
                stroke: new Stroke({
                  color: '#fff'
                }),
                fill: new Fill({
                  color: '#3399cc'
                })
              }),
              text: new Text({
                text: size.toString(), // 以聚合点的数量作为显示的内容
                fill: new Fill({
                  color: '#fff'
                })
              })
            })

            styleCache[size] = style
          }

          return style
        }
      })

      // 声明底图
      const raster = new Tile({
        source: new XYZ({
          url: 'https://api.maptiler.com/maps/topographique/256/{z}/{x}/{y}.png?key=B3EG5uYPUvFucEWVoCa3',
          crossOrigin: ''
        })
      })

      state.map = new Map({
        target: state.mapBox,
        layers: [raster, clusters],
        view: new View({
          center: [0, 0],
          zoom: 3
        })
      })
    }
    `
    return {
      code
    }
  }
}
</script>
